﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Documents
//  File name:	RedirectModule.cs
//  Developer:	Solomatov Igor
//  Created:	03.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.SharePoint;

namespace Smart.Documents.Modules
{
	public class RedirectModule : IHttpModule
	{
		#region IHttpModule Members

		public void Dispose()
		{
		}

		public void Init(HttpApplication context)
		{
			context.BeginRequest +=
				context_BeginRequest;
		}

		private void context_BeginRequest(object sender, EventArgs e)
		{
			var app = (HttpApplication) sender;
			var requestUrl = app.Request.Url.ToString();
			var regEx =
				new Regex(@"^https?://.*(?<itemUrl>/[^/]+\.[^/\.]+)$");

			if (regEx.IsMatch(requestUrl))
				return;

			if (!requestUrl.EndsWith("/",
			                         StringComparison.CurrentCulture))
				requestUrl += "/";

			var destinationUrl = String.Empty;

			SPSecurity.RunWithElevatedPrivileges(
				delegate
				{
					try
					{
						using (var site = new SPSite(requestUrl))
						{
							using (var web = site.OpenWeb())
							{
								/*
								if (web.IsPublishingWeb())
								{
									var publishingWeb =
										PublishingWeb.GetPublishingWeb(web);

									if (publishingWeb.DefaultPage.Url.
										EndsWith("/VariationRoot.aspx",
												 StringComparison.CurrentCultureIgnoreCase))
									{
										string defaultPage;

										using (var nlWeb = site.OpenWeb("nl"))
										{
											defaultPage =
												PublishingWeb.GetPublishingWeb(nlWeb)
													.DefaultPage.Url;
										}

										destinationUrl = String.Concat(requestUrl,
																	   "nl/", defaultPage);
									}
									else
										destinationUrl = String.Concat(requestUrl,
																	   publishingWeb.DefaultPage.Url);
								}
								else
								 */
								destinationUrl =
									String.Concat(requestUrl, "default.aspx");
							}
						}
					}
					catch (Exception)
					{
					}
				});

			if (String.IsNullOrEmpty(destinationUrl))
				return;

			app.Response.AddHeader("Location", destinationUrl);
			app.Response.StatusCode = 301;
		}

		#endregion
	}
}